package cn.edu.ncut.cs.springboot.petmanagementsystem.controller;

import cn.edu.ncut.cs.springboot.petmanagementsystem.common.PageResult;
import cn.edu.ncut.cs.springboot.petmanagementsystem.common.Result;
import cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.Product;
import cn.edu.ncut.cs.springboot.petmanagementsystem.mapper.ProductMapper;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.ProductService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/product")
@Tag(name = "宠物商品模块")
public class ProductController {

    @Autowired
    private ProductService productService;
    
    @Autowired
    private ProductMapper productMapper;

    // ==================== 模块三：商品模块增强新增接口 ====================

    @Operation(summary = "获取商品分类列表")
    @GetMapping("/categories")
    public Result<java.util.List<java.util.Map<String, Object>>> getProductCategories() {
        try {
            java.util.List<java.util.Map<String, Object>> categories = productService.getProductCategories();
            return Result.success("获取成功", categories);
        } catch (Exception e) {
            log.error("获取商品分类列表失败", e);
            return Result.error("获取失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取热门商品")
    @GetMapping("/hot")
    public Result<java.util.List<Product>> getHotProducts(
            @Parameter(description = "限制数量，默认10") @RequestParam(required = false, defaultValue = "10") Integer limit) {
        try {
            java.util.List<Product> products = productService.getHotProducts(limit);
            return Result.success("获取成功", products);
        } catch (Exception e) {
            log.error("获取热门商品失败", e);
            return Result.error("获取失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取推荐商品")
    @GetMapping("/recommend")
    public Result<java.util.List<Product>> getRecommendProducts(
            @Parameter(description = "限制数量，默认10") @RequestParam(required = false, defaultValue = "10") Integer limit) {
        try {
            java.util.List<Product> products = productService.getRecommendProducts(limit);
            return Result.success("获取成功", products);
        } catch (Exception e) {
            log.error("获取推荐商品失败", e);
            return Result.error("获取失败: " + e.getMessage());
        }
    }

    @Operation(summary = "商品库存检查")
    @GetMapping("/check-stock/{id}")
    public Result<Boolean> checkStock(
            @Parameter(description = "商品ID") @PathVariable Long id,
            @Parameter(description = "购买数量") @RequestParam Integer quantity) {
        try {
            Boolean available = productService.checkStock(id, quantity);
            return Result.success("检查完成", available);
        } catch (Exception e) {
            log.error("检查商品库存失败", e);
            return Result.error("检查失败: " + e.getMessage());
        }
    }

    // ==================== 原有接口 ====================

    @Operation(summary = "获取宠物商品列表（支持多条件动态查询）")
    @GetMapping("/list")
    public PageResult<Product> getProductList(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "分类ID（精确查询，2=玩具，3=日用品，4=医疗保健）") @RequestParam(required = false) Long categoryId,
            @Parameter(description = "分类名称/关键词（模糊查询，支持'狗粮'、'猫粮'等）") @RequestParam(required = false) String category,
            @Parameter(description = "商品名称（模糊查询）") @RequestParam(required = false) String productName,
            @Parameter(description = "关键词（搜索商品名称或描述，兼容旧版）") @RequestParam(required = false) String keyword,
            @Parameter(description = "最低价格") @RequestParam(required = false) java.math.BigDecimal minPrice,
            @Parameter(description = "最高价格") @RequestParam(required = false) java.math.BigDecimal maxPrice,
            @Parameter(description = "排序字段（price/sales/createTime）") @RequestParam(required = false) String orderBy,
            @Parameter(description = "排序方向（asc/desc）") @RequestParam(required = false, defaultValue = "desc") String order) {
        try {
            log.info("查询商品列表 - pageNum: {}, pageSize: {}, categoryId: {}, category: {}, productName: {}", 
                    pageNum, pageSize, categoryId, category, productName);
            log.info("价格范围: [{} - {}], keyword: {}, 排序: {} {}", 
                    minPrice, maxPrice, keyword, orderBy, order);
            
            // 构建查询条件
            com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<Product> queryWrapper = 
                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
            
            // 1. 分类查询（优先使用 categoryId）
            if (categoryId != null) {
                queryWrapper.eq(Product::getCategoryId, categoryId);
                log.info("使用 categoryId 查询: {}", categoryId);
            } else if (org.springframework.util.StringUtils.hasText(category) && !"all".equalsIgnoreCase(category)) {
                // 使用 category 进行模糊查询（商品名称）
                queryWrapper.like(Product::getProductName, category);
                log.info("使用 category 模糊查询: {}", category);
            }
            
            // 2. 商品名称搜索（优先使用 productName，兼容 keyword）
            String searchKeyword = org.springframework.util.StringUtils.hasText(productName) ? productName : keyword;
            if (org.springframework.util.StringUtils.hasText(searchKeyword)) {
                queryWrapper.and(wrapper -> 
                    wrapper.like(Product::getProductName, searchKeyword)
                           .or()
                           .like(Product::getDescription, searchKeyword)
                );
                log.info("商品名称搜索: {}", searchKeyword);
            }
            
            // 3. 价格范围
            if (minPrice != null) {
                queryWrapper.ge(Product::getPrice, minPrice);
            }
            if (maxPrice != null) {
                queryWrapper.le(Product::getPrice, maxPrice);
            }
            
            // 4. 只查询上架商品
            queryWrapper.eq(Product::getProductStatus, 1);
            
            // 5. 排序
            if (org.springframework.util.StringUtils.hasText(orderBy)) {
                boolean isAsc = "asc".equalsIgnoreCase(order);
                switch (orderBy.toLowerCase()) {
                    case "price":
                        queryWrapper.orderBy(true, isAsc, Product::getPrice);
                        break;
                    case "sales":
                        queryWrapper.orderBy(true, isAsc, Product::getSoldQuantity);
                        break;
                    case "createtime":
                        queryWrapper.orderBy(true, isAsc, Product::getCreateTime);
                        break;
                    default:
                        queryWrapper.orderByDesc(Product::getCreateTime);
                }
                log.info("使用排序: {} {}", orderBy, order);
            } else {
                queryWrapper.orderByDesc(Product::getCreateTime);
            }
            
            // 分页查询
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<Product> page = 
                    new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageNum, pageSize);
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<Product> result = 
                    productMapper.selectPage(page, queryWrapper);
            
            log.info("查询结果 - 总记录数: {}, 当前页: {}, 每页数量: {}, 总页数: {}", 
                     result.getTotal(), result.getCurrent(), result.getSize(), result.getPages());
            
            return PageResult.success(result);
        } catch (Exception e) {
            log.error("查询商品列表失败", e);
            return PageResult.pageError("查询失败: " + e.getMessage());
        }
    }

    @Operation(summary = "查看指定商品的详细信息")
    @GetMapping("/detail/{id}")
    public Result<Product> getProductDetail(
            @Parameter(description = "商品ID") @PathVariable Long id) {
        try {
            Product product = productService.getProductById(id);
            if (product != null) {
                return Result.success(product);
            }
            return Result.error("商品不存在");
        } catch (Exception e) {
            log.error("查询商品详情失败", e);
            return Result.error("查询失败");
        }
    }
}
